﻿using UnityEngine;
using System.Collections;

[AddComponentMenu("TheDice/UI/RenderSortingOrderSetting")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]

public class RenderSortingOrderSetting : MonoBehaviour
{
    public bool isNeedChildControl = false;

    [SerializeField]
    string layerName;
    public string LayerName
    {
        get { return layerName; }
        set
        { 
            layerName = value;

            if (isNeedChildControl)
                ChildControllerSortingLayerName(transform);
            else
            {
                gameObject.renderer.sortingLayerName = layerName;

                if (gameObject.particleSystem != null)
                    gameObject.particleSystem.renderer.sortingLayerName = layerName;
            }            
        }
    }
    [SerializeField]
    int orderInLayer;
    public int SortingOrder
    {
        get { return orderInLayer; }
        set 
        {
            orderInLayer = value;

            if (isNeedChildControl)
                ChildControllerSortingOrder(transform);
            else
            {               
                gameObject.renderer.sortingOrder = orderInLayer;

                if (gameObject.particleSystem != null)
                    gameObject.particleSystem.renderer.sortingOrder = orderInLayer;
            }
        }
    }

    void ChildControllerSortingLayerName(Transform tf)
    {
        if (tf.renderer != null)
            tf.renderer.sortingLayerName = LayerName;

        if (tf.particleSystem != null)
            tf.particleSystem.renderer.sortingLayerName = LayerName;

        if (tf.childCount > 0)
        {
            for(int i = 0 ; i < tf.childCount ; i++)
            {
                Transform temp = tf.GetChild(i);
                ChildControllerSortingLayerName(temp);
            }
        }
    }

    void ChildControllerSortingOrder(Transform tf)
    {
        if (tf.renderer != null)
            tf.renderer.sortingOrder = SortingOrder;

        if (tf.particleSystem != null)
            tf.particleSystem.renderer.sortingOrder = SortingOrder;

        if (tf.childCount > 0)
        {
            for (int i = 0; i < tf.childCount; i++)
            {
                Transform temp = tf.GetChild(i);
                ChildControllerSortingOrder(temp);
            }
        }
    }

    //void Awake()
    //{
    //    gameObject.renderer.sortingLayerName = LayerName;
    //    if (gameObject.particleSystem != null)
    //        gameObject.particleSystem.renderer.sortingLayerName = LayerName;

    //    gameObject.renderer.sortingOrder = OrderInLayer;
    //}
}
